<template>
  <div class="matrix-bg">
    <canvas ref="canvas" class="matrix-canvas"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const canvas = ref(null)
let ctx = null
let animationId = null
let drops = []

const matrix = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789@#$%^&*()*&^%+-/~{[|`]}";
const matrixArray = matrix.split("");

const initCanvas = () => {
  if (!canvas.value) return
  
  ctx = canvas.value.getContext('2d')
  canvas.value.width = window.innerWidth
  canvas.value.height = window.innerHeight
  
  const columns = canvas.value.width / 20
  
  // 初始化雨滴
  for (let x = 0; x < columns; x++) {
    drops[x] = 1
  }
  
  draw()
}

const draw = () => {
  // 半透明黑色背景，创建拖尾效果
  ctx.fillStyle = 'rgba(0, 0, 0, 0.04)'
  ctx.fillRect(0, 0, canvas.value.width, canvas.value.height)
  
  ctx.fillStyle = '#00ff00'
  ctx.font = '15px monospace'
  
  // 绘制字符
  for (let i = 0; i < drops.length; i++) {
    const text = matrixArray[Math.floor(Math.random() * matrixArray.length)]
    ctx.fillText(text, i * 20, drops[i] * 20)
    
    // 随机重置雨滴
    if (drops[i] * 20 > canvas.value.height && Math.random() > 0.975) {
      drops[i] = 0
    }
    
    drops[i]++
  }
  
  animationId = requestAnimationFrame(draw)
}

const handleResize = () => {
  if (!canvas.value) return
  canvas.value.width = window.innerWidth
  canvas.value.height = window.innerHeight
  
  const columns = canvas.value.width / 20
  drops.length = 0
  for (let x = 0; x < columns; x++) {
    drops[x] = 1
  }
}

onMounted(() => {
  initCanvas()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (animationId) {
    cancelAnimationFrame(animationId)
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.matrix-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  pointer-events: none;
}

.matrix-canvas {
  width: 100%;
  height: 100%;
  opacity: 0.1;
}
</style>